/*
 * @Author: czy
 * @Date: 2021-07-10 08:36:13
 * @LastEditTime: 2021-07-12 21:58:27
 */
#include "string.h"
#include "datetime.h"

#include "sys/system.h"

static time_t timestamp;

static char *month_str[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"};
static char *day_str[] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};

/**
 * @description: Converts a string to month.
 * @param str   String.
 * @return Month.
 */
static int str2mon(char *str)
{
    for (int i = 0; i < 12; i++)
    {
        if (strcmp(str, month_str[i]) == 0)
        {
            return i;
        }
    }
}

/**
 * @description: Converts a string to weekday.
 * @param str   String.
 * @return Weekday.
 */
static int str2day(char *str)
{
    for (int i = 0; i < 7; i++)
    {
        if (strcmp(str, day_str[i]) == 0)
        {
            return i;
        }
    }
}

/**
 * @description: Update time per second.
 */
static void update_time(void)
{
    timestamp++;
    settime(&timestamp);
}

/**
 * @description: Initialization.
 */
void communicate_init(void)
{
    tm start_time;
    char *datetime[5];
    char date_str[40];
    strcpy(date_str, __TIMESTAMP__);
    deblank(date_str);
    split(datetime, date_str, " ");
    start_time.tm_wday = str2day(datetime[0]);
    start_time.tm_mon = str2mon(datetime[1]);
    start_time.tm_mday = str2int(datetime[2]);
    char *time[3];
    split(time, datetime[3], ":");
    start_time.tm_hour = str2int(time[0]);
    start_time.tm_min = str2int(time[1]);
    start_time.tm_sec = str2int(time[2]);
    start_time.tm_year = str2int(datetime[4]);
    start_time.tm_msec = 0;
    
    timestamp = mktime(start_time);
    settime(&timestamp);
    timer(update_time, 1000);
}
